//
//  RockerView.swift
//  car
//
//  Created by 范俊伟 on 2024/1/11.
//

import SwiftUI
import CoreMotion

struct RockerView: View {
    var width: CGFloat
    
    @State var cx:CGFloat;
    @State var cy:CGFloat;
    @State var resetPoint:Bool = false;
    var ewidth:CGFloat
//    var onChangePoint: ((Int,Int) -> Void)?
#if os(iOS)
    var motionManager = CMMotionManager()
#endif
    var timeInterval: TimeInterval = 1
    @State var lastTime:Int = 0;
    @Binding var data:SaveData
    @Binding var isUserMotion:Bool
    func IntgetNow() -> Int{
        return Int(Date().timeIntervalSince1970*1000)
    }
    init(data: Binding<SaveData>, isUserMotion:Binding<Bool>){
        self._data = data
        self._isUserMotion = isUserMotion
        self.ewidth = 30
#if os(iOS)
        self.width = min(UIScreen.main.bounds.width,  UIScreen.main.bounds.height)
#else
        self.width = 500
#endif
        self.cx = self.width/2-self.ewidth/2.0;
        self.cy = self.width/2-self.ewidth/2.0;
//        if self.onChangePoint != nil {
//            self.onChangePoint!(0,0)
//        }
    }
#if os(iOS)
    func startGyroUpdates() {
         //判断设备支持情况
         guard motionManager.isGyroAvailable else {
             print("不支持陀螺仪")
             return
         }
          
         //设置刷新时间间隔
         self.motionManager.gyroUpdateInterval = self.timeInterval
          
         //开始实时获取数据
         let queue = OperationQueue.current
   
         self.motionManager.startDeviceMotionUpdates(to: queue!, withHandler: { (data, error) in
             guard error == nil else {
                 print(error!)
                 return
             }
             if(!self.isUserMotion){
                 if(!self.resetPoint){
                     self.resetPoint = true;
                     self.cx = self.width/2-self.ewidth/2.0;
                     self.cy = self.width/2-self.ewidth/2.0;
                     self.data = SaveData(x: 0, y: 0, beep: self.data.beep)
                 }
                 return
             }
             self.resetPoint = false
             
             // 有更新
             if self.motionManager.isDeviceMotionActive {
                 let data:CMDeviceMotion = data!
                 var yp = (abs(data.attitude.quaternion.y)-0.1)*100/(0.4-0.1)
                 if yp>100{yp=100}
                 if yp<0{yp=0}
                 if data.attitude.quaternion.y < 0 && yp != 0 {yp = -yp}
                 var xp = (abs(data.attitude.quaternion.x)-0.1)*100/(0.2-0.1)
                 if xp>100{xp=100}
                 if xp<0{xp=0}
                 if data.attitude.quaternion.x < 0 && xp != 0 {xp = -xp}
                 let x = self.width/2 + yp/100*self.width/2
                 let y = self.width/2 + xp/100*self.width/2
                 DispatchQueue.main.async {
                     self.cx = x-self.ewidth/2;
                     self.cy = y-self.ewidth/2;
                     let outx = Int((x-self.width/2)*100/(self.width/2))
                     let outy = Int((y-self.width/2)*100/(self.width/2))
                    
                     let now = self.IntgetNow()
                     if  now-self.lastTime>100 {
                         self.lastTime = now
                         self.data = SaveData(x: outx, y: outy, beep: self.data.beep)
                        
                     }
              }
              
                
             }
         })
     }
#endif
    var body: some View {
        ZStack{
            //            CircleImage().offset(x:cx,y:cy)
            Path { path in
            
                path.move(to: .init(x: self.width/2, y: self.width/2))
                path.addLine(to: .init(x: self.width/2-100, y: self.width/2))

                path.move(to: .init(x: self.width/2, y: self.width/2))
                path.addLine(to: .init(x: self.width/2, y: self.width/2-100))
                
                path.move(to: .init(x: self.width/2, y: self.width/2))
                path.addLine(to: .init(x: self.width/2, y: self.width/2+100))
                
                path.move(to: .init(x: self.width/2, y: self.width/2))
                path.addLine(to: .init(x: self.width/2+100, y: self.width/2))
                
                path.move(to: .init(x: self.width/2, y: 0))
                path.addLine(to: .init(x: self.width/2, y: 20))
                
                path.move(to: .init(x: self.width/2, y:self.width))
                path.addLine(to: .init(x: self.width/2, y:self.width-20))
                
                path.move(to: .init(x: 0, y:self.width/2))
                path.addLine(to: .init(x: 20, y:self.width/2))
                
                path.move(to: .init(x: self.width, y:self.width/2))
                path.addLine(to: .init(x: self.width-20, y:self.width/2))
                //
            }.stroke(style:StrokeStyle(lineWidth: 1, dash: [5]))
            
            Path { path in
            
                path.addEllipse(in: CGRectMake(self.cx, self.cy,self.ewidth, self.ewidth))

              
                //
            }.fill(Color.white).shadow(radius: 10)
            
        }.frame(width: self.width,height: self.width)
            .background(Color(hue: 1.0, saturation: 0.0, brightness: 0.95))
            .cornerRadius(/*@START_MENU_TOKEN@*/3.0/*@END_MENU_TOKEN@*/)
            .shadow(radius: 10)
            .gesture(DragGesture(minimumDistance: 0).onChanged { value in
                if(self.isUserMotion){
                    return
                }
                var x = value.location.x
                var y = value.location.y
                if x<0 {
                    x = 0
                }
                if y<0 {
                    y = 0
                }
                if x > self.width {
                    x = self.width
                }
                if y > self.width {
                    y = self.width
                }
                self.cx = x-self.ewidth/2;
                self.cy = y-self.ewidth/2;
                let outx = Int((x-self.width/2)*100/(self.width/2))
                let outy = Int((y-self.width/2)*100/(self.width/2))
                let now = self.IntgetNow()
                if  now-self.lastTime>100 {
                    self.lastTime = now
                    self.data = SaveData(x: outx, y: outy, beep: self.data.beep)
                }
            }.onEnded{_ in
                self.cx = self.width/2-self.ewidth/2;
                self.cy = self.width/2-self.ewidth/2;
                self.data = SaveData(x: 0, y: 0, beep: self.data.beep)
            })
            .task{
#if os(iOS)
                startGyroUpdates()
#endif
            }
    }
        
    
}

//#Preview {
//    RockerView()
//}
